package com.spring.security.config.security;

import com.spring.security.config.security.authentication.CustomWebAuthenticationDetails;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.authentication.dao.DaoAuthenticationProvider;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Component;

import java.util.Collection;

@Component
@Slf4j
public class MyAuthenticationProvider extends DaoAuthenticationProvider {
    public MyAuthenticationProvider(@Qualifier("userDetailService") UserDetailsService userDetailsService,
                                    PasswordEncoder passwordEncoder) {
        this.setUserDetailsService(userDetailsService);
        this.setPasswordEncoder(passwordEncoder);
    }


    @Override
    protected void additionalAuthenticationChecks(UserDetails userDetails, UsernamePasswordAuthenticationToken token) throws AuthenticationException {
        //添加校验逻辑
        String password = userDetails.getPassword();
        String username = userDetails.getUsername();
        Collection<? extends GrantedAuthority> authorities = userDetails.getAuthorities();

        CustomWebAuthenticationDetails details = (CustomWebAuthenticationDetails)token.getDetails();
        boolean imageCodeIsRight = details.getImageCodeIsRight();
        log.info("获取的details：{}", details);
        String principal = (String) token.getCredentials();
        boolean matches = this.getPasswordEncoder().matches(principal, password);
        super.additionalAuthenticationChecks(userDetails, token);
    }

    @Override
    public Authentication authenticate(Authentication authentication) throws AuthenticationException {
        Object details = authentication.getDetails();
        return super.authenticate(authentication);
    }
}
